package com.micro.controller;

import com.micro.dto.TrainMealOrderDTO;
import com.micro.entity.TrainMealOrder;
import com.micro.request.MealOrderRequest;
import com.micro.service.TrainMealOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping({"/api/train-meal-orders", "/api/meal-orders"})
public class TrainMealOrderController {

    private static final Logger logger = LoggerFactory.getLogger(TrainMealOrderController.class);

    @Autowired
    private TrainMealOrderService trainMealOrderService;

    // 创建火车餐订单
    @PostMapping
    public ResponseEntity<TrainMealOrder> createOrder(@RequestBody MealOrderRequest request) {
        try {
            logger.info("开始创建火车餐订单，用户: {}, 车票订单ID: {}", request.getUsername(), request.getTrainTicketOrderId());
            TrainMealOrder order = trainMealOrderService.createOrder(request);
            logger.info("火车餐订单创建成功，订单ID: {}", order.getOrderId());
            return ResponseEntity.ok(order);
        } catch (Exception e) {
            logger.error("创建火车餐订单失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    // 更新订单状态
    @PutMapping("/{orderId}/status")
    public ResponseEntity<Void> updateOrderStatus(
            @PathVariable Long orderId,
            @RequestParam String status) {
        try {
            logger.info("更新订单状态，订单ID: {}, 新状态: {}", orderId, status);
            trainMealOrderService.updateOrderStatus(orderId, status);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            logger.error("更新订单状态失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    // 根据用户名获取订单列表
    @GetMapping("/user/{username}")
    public ResponseEntity<List<TrainMealOrderDTO>> getOrdersByUsername(@PathVariable String username) {
        try {
            List<TrainMealOrderDTO> orders = trainMealOrderService.getOrdersByUsername(username);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            logger.error("获取用户订单失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    // 兼容前端调用的接口路径
    @GetMapping
    public ResponseEntity<List<TrainMealOrderDTO>> getOrdersByUsernameParam(@RequestParam String username) {
        try {
            List<TrainMealOrderDTO> orders = trainMealOrderService.getOrdersByUsername(username);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            logger.error("获取用户订单失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    // 根据用户ID获取订单列表
    @GetMapping("/user-id/{userId}")
    public ResponseEntity<List<TrainMealOrder>> getUserOrders(@PathVariable Long userId) {
        try {
            List<TrainMealOrder> orders = trainMealOrderService.getUserOrders(userId);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            logger.error("获取用户订单失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    // 根据订单ID获取订单详情
    @GetMapping("/{orderId}")
    public ResponseEntity<TrainMealOrder> getOrderDetails(@PathVariable Long orderId) {
        try {
            TrainMealOrder order = trainMealOrderService.getOrderDetails(orderId);
            if (order != null) {
                return ResponseEntity.ok(order);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("获取订单详情失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    // 兼容前端调用的订单详情接口
    @GetMapping("/{orderId}/details")
    public ResponseEntity<TrainMealOrder> getOrderDetailsByPath(@PathVariable Long orderId) {
        try {
            TrainMealOrder order = trainMealOrderService.getOrderDetails(orderId);
            if (order != null) {
                return ResponseEntity.ok(order);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("获取订单详情失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    // 根据订单状态获取订单列表
    @GetMapping("/status/{status}")
    public ResponseEntity<List<TrainMealOrder>> getOrdersByStatus(@PathVariable String status) {
        try {
            List<TrainMealOrder> orders = trainMealOrderService.getOrdersByStatus(status);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            logger.error("根据状态获取订单失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    // 根据列车ID获取订单列表
    @GetMapping("/train/{trainId}")
    public ResponseEntity<List<TrainMealOrder>> getOrdersByTrainId(@PathVariable Long trainId) {
        try {
            List<TrainMealOrder> orders = trainMealOrderService.getOrdersByTrainId(trainId);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            logger.error("根据列车ID获取订单失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    // 根据订单编号获取订单
    @GetMapping("/order-number/{orderNumber}")
    public ResponseEntity<TrainMealOrder> getOrderByOrderNumber(@PathVariable String orderNumber) {
        try {
            TrainMealOrder order = trainMealOrderService.getOrderByOrderNumber(orderNumber);
            if (order != null) {
                return ResponseEntity.ok(order);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("根据订单编号获取订单失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
}
